
#include <QtWidgets>
#include "RVMSUtil.h"


static int parsingRTSPURL(char const* url, char* username, char* password, char* address, int* portNum, char* path)
{
	// Parse the URL as "rtsp://[<username>[:<password>]@]<server-address-or-name>[:<port>][/<path>]"
	uint32_t const prefixLength = 7;
	char const* from = &url[prefixLength];
	char const* tmpPos;

	if ((tmpPos = strchr(from, '@')) != NULL) {
		// We found <username> (and perhaps <password>).
		char const* usernameStart = from;
		char const* passwordStart = NULL;
		char const* p = tmpPos;

		if ((tmpPos = strchr(from, ':')) != NULL && tmpPos < p) {
			passwordStart = tmpPos;
			uint32_t passwordLen = p - passwordStart - 1;
			strncpy(password, passwordStart + 1, passwordLen);
			password[passwordLen] = '\0'; //Set the ending character.
		}

		uint32_t usernameLen = 0;
		if (passwordStart != NULL) {
			usernameLen = tmpPos - usernameStart;
		}
		else {
			usernameLen = p - usernameStart;
		}
		strncpy(username, usernameStart, usernameLen);
		username[usernameLen] = '\0';  //Set the ending character.

		from = p + 1; // skip the '@'
	}

	const char* pathStart = NULL;
	if ((tmpPos = strchr(from, '/')) != NULL) {
		uint32_t pathLen = strlen(tmpPos + 1);  //Skip '/'
		strncpy(path, tmpPos + 1, pathLen + 1);
		pathStart = tmpPos;
	}

	// Next, will parse the address and port.
	tmpPos = strchr(from, ':');
	if (tmpPos == NULL) {
		if (pathStart == NULL) {
			uint32_t addressLen = strlen(from);
			strncpy(address, from, addressLen + 1);  //Already include '\0'
		}
		else {
			uint32_t addressLen = pathStart - from;
			strncpy(address, from, addressLen);
			address[addressLen] = '\0';   //Set the ending character.
		}
		*portNum = 554; // Has not the specified port, and will use the default value
	}
	else if (tmpPos != NULL) {
		uint32_t addressLen = tmpPos - from;
		strncpy(address, from, addressLen);
		address[addressLen] = '\0';  //Set the ending character.
		*portNum = strtoul(tmpPos + 1, NULL, 10);
	}
	return 1;
}

RTSP_URL_Component parseRtspURL(const QString& url)
{
	char url_cstr[512];
	QByteArray c = url.toLocal8Bit();
	strcpy(url_cstr, c.data());

	char username[512] = { 0 };
	char password[512] = { 0 };
	char address[512] = { 0 };
	int portNum = 0;
	char path[512] = { 0 };
	RTSP_URL_Component value;
	value.RTSPPort = 0; 

	int rt = parsingRTSPURL(url_cstr, username, password, address, &portNum, path);

	value.userName = username; 
	value.password = password; 
	value.IPAddr = address; 
	value.RTSPPort = portNum; 
	value.Path = path; 

	return value;

}